import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'
// import { meta } from '@babel/eslint-parser'
// import HomeView from '../views/HomeView.vue'

Vue.use(VueRouter)

const routes = [
  // {
  //   path: '/',
  //   name: 'home',
  //   component: HomeView
  // },
  // {
  //   path: '/about',
  //   name: 'about',
  //   // route level code-splitting
  //   // this generates a separate chunk (about.[hash].js) for this route
  //   // which is lazy-loaded when the route is visited.
  //   component: () => import(/* webpackChunkName: "about" */ '../views/AboutView.vue')
  // }
  {
    path: '/',
    redirect: '/datadisplay',
    component: () => import('../views/LoginAndRegister.vue')
  },
  {
    path: '/datadisplay',
    name: 'datadisplay',
    component: () => import('../views/DataDisplay.vue'),
    meta: {
      // requiresAuth: true // 需要认证的页面 
    }
  },
  {
    path: '/login',
    name: '/login',
    component: () => import('../views/LoginAndRegister.vue'),
    meta: {
      guestOnly:true
    }
  }
]

const router = new VueRouter({
  routes
})

router.beforeEach((to, from, next) => {
  // const isAuthenticated = checkAuthStatus() // 检查登录状态的方法
  const isAuthenticated = store.state.isAuthenticated

  // 需要认证的页面且未登录
  if (to.matched.some(record => record.meta.requiresAuth)) {
    if (!isAuthenticated) {
      next({
        path: '/login',
        query: { redirect: to.fullPath } // 保存目标路径
      })
    } else {
      next()
    }
  }
  // 仅允许未登录访问的页面
  else if (to.matched.some(record => record.meta.guestOnly)) {
    if (isAuthenticated) {
      next({ path: '/datadisplay' }) // 已登录用户禁止访问登录页
    } else {
      next()
    }
  }
  // 其他情况
  else {
    next()
  }
})

export default router
